/*
 Copyright 2009 Christian Sprecher

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

import net.miginfocom.swing.MigLayout
import widgets.JcrTransferHandler
import javax.swing.DefaultComboBoxModel
import widgets.PropertyViewerPanel
import java.awt.LayoutManager
import java.awt.Point
import widgets.JcrTreeCellRenderer
import javax.swing.KeyStroke
import javax.swing.InputMap
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JFileChooser


actions {
    action(id: 'changeLoginTypeAction',
            name: "Type",
            closure: controller.changeLoginType,
    )
    action(id: 'loginAction',
            name: "Login",
            closure: controller.login,
            mnemonic: 'L',
            accelerator: 'L',
    )
    action(id: 'logoutAction',
            name: "Logout",
            closure: controller.logout,
            mnemonic: 'O',
            accelerator: 'O',
    )
    action(id: 'addNodeAction',
            name: "Add Node",
            closure: controller.addNode,
            mnemonic: 'A',
            accelerator: 'A',
    )
    action(id: 'renameNodeAction',
            name: "Rename Node",
            closure: controller.renameNode,
            mnemonic: 'R',
            accelerator: 'R',
    )
    action(id: 'removeNodeAction',
            name: "Remove Node",
            closure: controller.removeNode,
            mnemonic: 'A',
            accelerator: 'A',
    )
    action(id: 'addPropertyAction',
            name: "Add Property",
            closure: controller.addProperty,
    )
    action(id: 'RemovePropertyAction',
            name: "Remove Property",
            closure: controller.removeProperty,
    )
}

    def layoutAttr = 'fill, insets 10, top, left'
bindGroup(id:'propertyBinding')
application(title: 'JCR Manager',  size:[320,600], location:[50,50], pack: true, locationByPlatform: true) {
    panel(layout:  new MigLayout(layoutAttr)) {
        tabbedPane(id: 'mainTabbedPane', constraints: 'grow,width 500::') {
            panel(title: 'Connection', layout: new MigLayout('wrap','[pref!]10[fill,500]')) {
                label('Type:', constraints: 'left')
                comboBox(id: 'connectionType', action: changeLoginTypeAction)
                label('URI:')
                textField('rmi://localhost:1099/jackrabbit', id: 'connectionURI', constraints: 'split 2')
                button("...", constraints: 'width pref!', actionPerformed: {
                    def openResult = fileChooser.showOpenDialog()
    	            if (JFileChooser.APPROVE_OPTION == openResult) {
    		            connectionURI.text = fileChooser.selectedFile.toString()
    	            }
                })
                label('User Name:')
                textField(id: 'username')
                label('Passwort:')
                passwordField(id: 'password')
                button('Login', id: 'loginButton', action: loginAction, constraints: 'sg, split 2')
                button('Logout', id: 'logoutButton', action: logoutAction, constraints: 'sg,wrap')
                label("""<html>
                <h3>Note on Login Types:
                <ul>
                <li><b>Remote:</b>Use this to access a repository via RMI.
                </li>
                <li><b>Local:</b>Accesses a repository directly by specifing a
                repository config file (typically named "repository.xml"). The repository location has to be
                in a directory named "repository" relative to the file. If no argument is supported, a repository
                is created in the same directory as the application is started.
                </li>
                </ul>
                """, constraints:'height 300, width 400, span 2')
            }
           panel(id:'repositoryBrowserPanel', title: 'Rep. Browser', layout: new MigLayout('fill,wrap','[200, fill, grow 20][500, fill, grow 100]','[fill, top][fill, top]')) {
                scrollPane(id:'treeScrollPane') {
                    tree(id: 'browserTree', cellRenderer: new JcrTreeCellRenderer(),
                        transferHandler: new JcrTransferHandler(), dragEnabled:true)
                        // Handler for DELETE key in the tree:
                        browserTree.registerKeyboardAction(removeNodeAction,
                            KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false),
                            JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
                        )
                }
                tabbedPane(id:'propertiesTabbedPane') {
                    panel(layout: new MigLayout(layoutAttr), title: 'Properties') {
                        scrollPane(constraints: 'grow, height max, width max') {
                            table(id:'propertiesTable')
                         }
                        panel(layout: new MigLayout('fill, insets 0'), constraints: 'wrap, top') {

                            button('Add', constraints: 'sg, wrap, top', actionPerformed: {
                             newPropertyDialog.pack()
                             newPropertyDialog.locationRelativeTo=propertiesTable
                             newPropertyDialog.show()
                            })
                            button('Remove', constraints: 'sg, wrap, top', actionPerformed:controller.removeProperty)
                        }
                        panel(id: 'valuePanel', constraints: 'wrap, spanx 3, grow, height max, width max')
                    }
                    panel(title: 'Multimedia View', id:'multiMediaPanel', layout: new MigLayout("fill")) {
                    }
                }
//               splitPane(leftComponent:treeScrollPane,rightComponent:propertiesTabbedPane)
            }
        }

        scrollPane(constraints: 'dock south, height 200:200:200, width 800') {
            infoTB = textArea(editable: true, dragEnabled:true, lineWrap: true, border: titledBorder('Log'), id: 'info', constraints: 'left, top')
            
        }
    }
}
popupMenu(id:'propertiesTablePopup', label:'Properties', invoker:propertiesTable) {
    menuItem('New', actionPerformed: {
//        newNodeDialog.pack()
//        newNodeDialog.locationRelativeTo=browserTreePopup
//        newNodeDialog.show()
    })
    menuItem('Delete', actionPerformed: controller.removeProperty)
}
popupMenu(id:'browserTreePopup', label:'label', invoker:browserTree) {
    menuItem('New', actionPerformed: {
        newNodeDialog.pack()
        newNodeDialog.locationRelativeTo=browserTreePopup
        newNodeDialog.show()
    })
    menuItem('Copy', actionPerformed: {
        browserTree.actionMap.parent.get("copy").actionPerformed(it)
    })
    menuItem('Paste', actionPerformed: {
        browserTree.actionMap.parent.get("paste").actionPerformed(it)
    })
    menuItem('Delete', actionPerformed: controller.removeNode)
    //TODO: checkout, save, etc
}
dialog(id:'newPropertyDialog', title: 'Add Property') {
    panel(layout:  new MigLayout(layoutAttr)) {
        label('Name')
        def name= textField( id:'newPropertyName', columns: 50, constraints: 'wrap')
        bind(source: newPropertyName, sourceProperty:'text', target:model.currentProperty,targetProperty:'name')
        label('Type')
        //TODO selection box, depending on node constraints
        def type = comboBox(id:'propertyType', constraints: 'wrap')
        bind(source: propertyType, sourceProperty:'selectedItem', target:model.currentProperty,targetProperty:'type')
        label('Multiple')
        checkBox(id:'propertyMultiple', constraints: 'wrap')
        button('Add', constraints: 'left, sg',  action:addPropertyAction)
    }
}

dialog(id:'newNodeDialog', title: 'Create New Node') {
    panel(layout:  new MigLayout(layoutAttr)) {
        label('Name')
        def name= textField( id:'newNodeName', columns: 50, constraints: 'wrap')
        bind(source: newNodeName, sourceProperty:'text', target:model,targetProperty:'newNodeName')
        label('Type')
        //TODO selection box, depending on node constraints
//        def type = comboBox(id:'newNodeType', constraints: 'wrap')
//        bind(source: newNodeType, sourceProperty:'selectedItem', target:model,targetProperty:'newNodeType')
        def type = textField(id:'newNodeType', columns: 50, constraints: 'wrap')
        bind(source: newNodeType, sourceProperty:'text', target:model,targetProperty:'newNodeType')
        button('Add', constraints: 'left, sg',  action:addNodeAction)
        //TODO: if there are mandatory child nodes, handle here
    }
}
fileChooser(id:'fileChooser')
